from datetime import timedelta
from typing import Any, List

from fastapi import Depends, HTTPException, APIRouter
from fastapi.encoders import jsonable_encoder
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from fastapi_common.api import deps
from fastapi_common.core import security
from fastapi_common.core.config import settings
from fastapi_common import crud
from fastapi_common import schemas
from fastapi_common import models

router = APIRouter()


@router.post("/login/access-token", tags=["login"])
async def login_access_token(
        db: Session = Depends(deps.get_db), form_data: OAuth2PasswordRequestForm = Depends()
) -> Any:
    user = crud.user.authenticate(
        db, email=form_data.username, password=form_data.password
    )
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect email or password")
    elif not crud.user.is_active(user):
        raise HTTPException(status_code=400, detail="Inactive user")
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    token_payload = {'user_id': user.id, 'role_id': user.role_id}
    access_token = security.create_access_token(
        token_payload, expires_delta=access_token_expires
    )
    return {
        "access_token": access_token,
        "token_type": "bearer",
    }


@router.get("/me/info", tags=["users"])
async def user_info(
        *,
        db: Session = Depends(deps.get_db),
        current_user: models.User = Depends(deps.get_current_active_user),
):
    res = jsonable_encoder(current_user)
    menus = crud.menu.list_menu_by_role(db, current_user.role_id)
    res['menus'] = menus
    return res


@router.post("/user/create", tags=["users"], response_model=schemas.User)
async def create_user(
        *,
        db: Session = Depends(deps.get_db),
        user_in: schemas.UserCreate
):
    return crud.user.create(db, obj_in=user_in, is_commit=True)
